Máster en Data Science UAH

Tasador de viviendas de alquiler vacacional en Lisboa

Notebook #3 - Estudio de la localización

Alumno: Héctor Mateos Oblanca
Tutor: Daniel Rodríguez Pérez

Intro

In [1]:
city = 'lisboa'
month = '201909'
filename_in = 'src/data/' + city + '-' + month + '-listings-CLEAN.csv'
In [2]:
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, HTML
import featuretools as ft
import uuid
import s2sphere as s2
import random
 
import catboost as cb
from kmodes.kmodes import KModes
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score, cross_val_predict 
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error

import scipy.spatial as spatial
import plotly.express as px
import chart_studio.plotly as py
import plotly.graph_objs as go
from plotly.offline import iplot, init_notebook_mode
import shap

%run src/utils.py
In [3]:
coefs = {}
metrics = {}

def collect_results(columns, model, method, r2, mae, mse, skip_coef=True):
    # coefs
    if skip_coef != True:
        method_coefs = {}
        if hasattr(model, '__intercept'):
            method_coefs['__intercept'] = model.intercept_
        
        for i in range(len(columns.values)):
            method_coefs[columns.values[i]] = abs(model.coef_[i])
        coefs[method] = method_coefs
        df_coefs = pd.DataFrame(coefs)
        df_coefs = df_coefs.sort_values(by=method, ascending=False)
        display(df_coefs)
    
    # metrics
    metrics[method] = {
        'R2':r2.round(3),
        'MAE':mae.round(3),
        'MSE':mse.round(3)
    }
    
    display(pd.DataFrame(metrics))

def print_feature_importances(method, importances, df):
    feature_score = pd.DataFrame(list(zip(df.dtypes.index, importances)), columns=['Feature','Score'])
    feature_score = feature_score.sort_values(by='Score', 
                                              ascending=True, 
                                              inplace=False, 
                                              kind='quicksort', 
                                              na_position='last')
    
    fig = go.Figure(
        go.Bar(
            x=feature_score['Score'],
            y=feature_score['Feature'],
            orientation='h'
        )
    )
    
    fig.update_layout(
        title=method + " Feature Importance Ranking",
        height=25*len(feature_score)
    )
    
    fig.show()

Carga del dataset

In [4]:
df = pd.read_csv(filename_in)
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 17756 entries, 0 to 17755
Data columns (total 61 columns):
host_response_time                      17756 non-null object
latitude                                17756 non-null float64
longitude                               17756 non-null float64
property_type                           17756 non-null object
room_type                               17756 non-null object
accommodates                            17756 non-null int64
bathrooms                               17756 non-null float64
bedrooms                                17756 non-null float64
price                                   17756 non-null float64
security_deposit                        17756 non-null float64
cleaning_fee                            17756 non-null float64
guests_included                         17756 non-null int64
extra_people                            17756 non-null float64
minimum_nights_avg_ntm                  17756 non-null float64
maximum_nights_avg_ntm                  17756 non-null float64
number_of_reviews                       17756 non-null int64
number_of_reviews_ltm                   17756 non-null int64
first_review                            17756 non-null object
last_review                             17756 non-null object
review_scores_rating                    17738 non-null float64
review_scores_accuracy                  17736 non-null float64
review_scores_cleanliness               17737 non-null float64
review_scores_checkin                   17737 non-null float64
review_scores_communication             17738 non-null float64
review_scores_location                  17738 non-null float64
review_scores_value                     17738 non-null float64
instant_bookable                        17756 non-null int64
cancellation_policy                     17756 non-null object
reviews_per_month                       17756 non-null float64
district                                17756 non-null object
neighbourhood                           17756 non-null object
has_wifi                                17756 non-null int64
has_essentials                          17756 non-null int64
has_kitchen                             17756 non-null int64
has_heating                             17756 non-null int64
has_washer                              17756 non-null int64
has_hangers                             17756 non-null int64
has_tv                                  17756 non-null int64
has_hair_dryer                          17756 non-null int64
has_iron                                17756 non-null int64
has_shampoo                             17756 non-null int64
has_laptop_friendly_workspace           17756 non-null int64
has_air_conditioning                    17756 non-null int64
has_hot_water                           17756 non-null int64
has_elevator                            17756 non-null int64
has_refrigerator                        17756 non-null int64
has_dishes_and_silverware               17756 non-null int64
has_microwave                           17756 non-null int64
has_bed_linens                          17756 non-null int64
has_no_stairs_or_steps_to_enter         17756 non-null int64
has_coffee_maker                        17756 non-null int64
has_cooking_basics                      17756 non-null int64
has_family/kid_friendly                 17756 non-null int64
has_long_term_stays_allowed             17756 non-null int64
has_first_aid_kit                       17756 non-null int64
has_oven                                17756 non-null int64
has_stove                               17756 non-null int64
has_license                             17756 non-null int64
activity_months                         17756 non-null float64
income_med_occupation                   17756 non-null float64
price_med_occupation_per_accommodate    17756 non-null float64
dtypes: float64(21), int64(32), object(8)
memory usage: 8.3+ MB

Descarte de características

In [5]:
# TO-DO explicar

useful_cols = [
    'accommodates',
    'bathrooms',
    'bedrooms',
    'cancellation_policy',
    'cleaning_fee',
    'extra_people',
    'guests_included',
    'has_air_conditioning',
    'has_bed_linens',
    'has_coffee_maker',
    'has_cooking_basics',
    'has_dishes_and_silverware',
    'has_elevator',
    'has_essentials',
    'has_family/kid_friendly',
    'has_first_aid_kit',
    'has_hair_dryer',
    'has_hangers',
    'has_heating',
    'has_hot_water',
    'has_iron',
    'has_kitchen',
    'has_laptop_friendly_workspace',
    'has_license',
    'has_long_term_stays_allowed',
    'has_microwave',
    'has_no_stairs_or_steps_to_enter',
    'has_oven',
    'has_refrigerator',
    'has_shampoo',
    'has_stove',
    'has_tv',
    'has_washer',
    'has_wifi',
    'instant_bookable',
    'latitude',
    'longitude',
    'maximum_nights_avg_ntm',
    'minimum_nights_avg_ntm',
    'neighbourhood',
    'price',
    'property_type',
    'room_type',
    'security_deposit'
]

useless_cols = [
    'district',
    'income_med_occupation',
    'activity_months',
    'host_response_time',
    'host_verified_by_phone',
    'host_verified_by_email',
    'host_verified_by_government_id',
    'host_verified_by_reviews',
    'host_verified_by_jumio',
    'host_verified_by_offline_government_id',
    'host_verified_by_selfie',
    'host_verified_by_identity_manual',
    'host_verified_by_facebook',
    'host_verified_by_work_email',
    'host_verified_by_google',
    'first_review',
    'last_review',
    'number_of_reviews',
    'number_of_reviews_ltm',
    'review_scores_rating',
    'review_scores_accuracy',
    'review_scores_cleanliness',
    'review_scores_checkin',
    'review_scores_communication',
    'review_scores_location',
    'review_scores_value',
    'reviews_per_month'
]

highly_corr_cols = [
    'has_refrigerator', 
    'host_verified_by_selfie'
]

df.drop([*useless_cols, *highly_corr_cols], axis=1, errors='ignore', inplace=True)
df.shape
Out[5]:
(17756, 44)

Nuevas características de localización calculadas

Distancia a puntos de interés

Se calcula para cada propiedad la distancia en kilómetros a diferentes puntos de interés turístico de la ciudad.

In [6]:
pois = [    
    {'name':'rossio', 'coord':(38.71398, -9.13825)},
    {'name':'jeronimos', 'coord':(38.69778, -9.20611)},
    {'name':'torre-belem', 'coord':(38.6916, -9.2160)},
    {'name':'m-pombal', 'coord':(38.723546, -9.149648)},
    {'name':'barrio-alto', 'coord':(38.7128, -9.1451)},
    {'name':'praca-do-comercio', 'coord':(38.7075, -9.1364)},
    {'name':'airport', 'coord':(38.7756, -9.1354)}
]
In [7]:
for poi in pois:
    df['dist_' + poi['name']] = df.apply(
        lambda r: get_haversine_distance(
            r['latitude'], 
            r['longitude'], 
            poi['coord']), 
        axis=1)

Clustering de barrios

La característica neighbourhood tiene una cardinalidad muy alta que puede conducir a sobreajuste puesto que en algunos barrios hay pocos datos. Se propone, utilizando clusterización, una característica de cardinalidad intermedia entre barrios y distritos que agrupe barrios similares y que resulte más representativa para el estudio.

In [8]:
km = KModes(n_clusters=15, init='Huang', n_init=10, random_state=42)
df['nb_cluster'] = km.fit_predict(df[['price_med_occupation_per_accommodate', 'neighbourhood']])
clusters = df['nb_cluster'].copy()
df['nb_cluster'] = df['nb_cluster'].apply(lambda x: 'nb_' + str(x))
df.drop(['price_med_occupation_per_accommodate'], axis=1, inplace=True) # solo era para calcular clusters
In [9]:
cluster_map = pd.DataFrame(list(zip(df['neighbourhood'], clusters)), columns=['nb', 'cluster'])
cluster_map.drop_duplicates(inplace=True)

with open('src/geo/' + city + '.neighbourhoods.geojson') as f:
    city_nb = fix_geojson(json.load(f))
    
fig = go.Figure(go.Choroplethmapbox(
    geojson=city_nb,
    locations=cluster_map['nb'], 
    z=cluster_map['cluster'],                   
    colorscale=px.colors.qualitative.Vivid,                                
    marker_opacity=0.5, 
    marker_line_width=0.2
))

fig.update_layout(
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0},
    title='clusters',
    showlegend=False
)

fig.show()

Celdas S2

In [10]:
def get_s2(lat, lng):
    py_cellid = s2.CellId.from_lat_lng(
        s2.LatLng.from_degrees(lat, lng)
    )
    py_cellid = py_cellid.parent(12)
    return 's2_' + str(py_cellid.id())

df['s2'] = df.apply(lambda r: get_s2(r['latitude'], r['longitude']), axis=1)
In [11]:
df_s2 = df[['s2', 'latitude', 'longitude']]
s2_cells = sorted(df_s2['s2'].unique())
random.shuffle(s2_cells)
df_s2['idx'] = df_s2['s2'].apply(lambda x: s2_cells.index(x))
In [12]:
fig314 = go.Figure()

fig314.add_trace(go.Scattermapbox(
    lon=df_s2['longitude'],
    lat=df_s2['latitude'],
    mode='markers',
    marker_color=df_s2['idx'],
    text=df_s2['idx'],
    marker=dict(
        size=5,
        opacity=0.4,
        colorscale='spectral'
    )
))

fig314.update_layout(
    showlegend=False,
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig314.show()

Regiones Voronoi

In [13]:
poi_coords = list(map(lambda x: x['coord'], pois))
vor = spatial.Voronoi(poi_coords)

def get_voronoi_index(row):
    new_point = [row['latitude'], row['longitude']]
    point_index = np.argmin(np.sum((vor.points - new_point)**2, axis=1))
    return 'v_' + str(point_index)

df['voronoi'] = df.apply(lambda r: get_voronoi_index(r), axis=1)
spatial.voronoi_plot_2d(vor)
Out[13]:
In [14]:
df_voronoi = df[['voronoi', 'latitude', 'longitude']]
voronoi_cells = sorted(df_voronoi['voronoi'].unique())
df_voronoi['idx'] = df_voronoi['voronoi'].apply(lambda x: voronoi_cells.index(x))
In [15]:
fig315 = go.Figure()

fig315.add_trace(go.Scattermapbox(
    lon=df_voronoi['longitude'],
    lat=df_voronoi['latitude'],
    mode='markers',
    marker_color=df_voronoi['idx'],
    text=df_voronoi['idx'],
    marker=dict(
        size=5,
        opacity=0.4,
        colorscale='spectral'
    )
))

fig315.add_trace(
    go.Scattermapbox(
        lat=list(map(lambda x: x['coord'][0], pois)),
        lon=list(map(lambda x: x['coord'][1], pois)),
        text=list(map(lambda x: x['name'], pois)),
        mode='markers',
        marker=dict(
            size=8,
            opacity=0.9,
            color='black'
        )
    )
)

fig315.update_layout(
    showlegend=False,
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig315.show()

Conversión de características categóricas en dummies

In [16]:
print(df.shape)
dfd = pd.get_dummies(df)
print(dfd.shape)

target = 'price'
features = list(dfd.columns)
features.remove(target)
(17756, 53)
(17756, 486)

Partición en conjuntos de entrenamiento y test

In [17]:
x_train, x_test, y_train, y_test = train_test_split(
    dfd[features], 
    dfd[target],
    test_size=0.3,
    random_state=42
)

x_train = x_train.astype(float) # prevent conversion warnings

Modelo base: Random Forest

In [18]:
def eval_model(method, cols, df):
    model = RandomForestRegressor(random_state=42, n_estimators=200)    
    regressor = Pipeline([('model', model)])
    regressor.fit(x_train[cols], y_train)
    y_pred = regressor.predict(x_test[cols])
    r2 = r2_score(y_test, y_pred)
    mae = mean_absolute_error(y_test, y_pred)
    mse = mean_squared_error(y_test, y_pred)
    
    collect_results(cols, model, method, r2, mae, mse, skip_coef=True)
    importances = regressor.named_steps['model'].feature_importances_
    print_feature_importances(method, importances, df[cols])
    return y_pred

Estudio de la localización

In [19]:
neighbourhood_cols = [col for col in dfd if col.startswith('neighbourhood')]
dist_cols = [col for col in dfd if col.startswith('dist_')]
coord_cols = ['latitude', 'longitude']
nb_cluster_cols = [col for col in dfd if col.startswith('nb_cluster_')]
s2_cols = [col for col in dfd if col.startswith('s2_')]
voronoi_cols = [col for col in dfd if col.startswith('voronoi')]

Modelo sin variable geográfica

Este modelo registraría toda la variabilidad de precio que es debida a las propiedades de las viviendas sin considerar caractarísticas geográficas de ningún tipo.

In [20]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('NO-GEO', cols, dfd)
NO-GEO
MAE 18.507
MSE 947.353
R2 0.623

Residuos

Se busca si existen zonas con un error positivo o negativo.

  • Lo que se puede asociar con puntos de interés: positivo
  • Zonas que los visitantes prefieren evitar: negativo
In [21]:
x_test['resid'] = y_test - y_pred
plt.hist(x_test['resid'], bins=50)
plt.show()

Residuos outliers

In [22]:
x_test2 = x_test.copy()
x_test2.reset_index(inplace=True)
outliers_idx = get_outliers_iqr(x_test2['resid'])[0]
remove_outliers(x_test2, outliers_idx, 'resid')
outliers between following bounds: -47.924437500000145 41.06006250000007
457 outliers to be removed with values: [-201.67650000000003, -194.8725000000003, -165.762, -164.8710000000005, -161.95500000000007, -147.4245000000003, -138.4874999999999, -134.25749999999994, -130.3875, -126.35999999999996, -125.151, -121.63499999999993, -114.19199999999992, -112.63049999999993, -111.79199999999986, -109.02599999999995, -108.80549999999997, -107.67149999999992, -105.10650000000001, -104.80580844155845, -100.42200000000005, -99.3195, -96.96149999999994, -96.54750000000001, -96.22800000000002, -94.61699999999996, -93.24449999999993, -92.84399999999988, -92.39549999999971, -91.93499999999989, -89.04600000000002, -88.11749999999986, -87.6645, -87.53399999999998, -86.62949999999995, -85.2345, -84.82049999999998, -84.42899999999997, -83.69999999999995, -83.25450000000004, -83.21849999999992, -82.66049999999998, -82.21274999999997, -81.94950000000003, -81.61650000000016, -80.64000000000004, -80.41049999999984, -79.86150000000004, -79.46549999999999, -79.31699999999998, -78.714, -78.55050000000001, -78.237, -77.67450000000001, -77.32199999999997, -76.02749999999997, -75.94199999999995, -75.80250000000001, -74.34449999999998, -74.05425000000005, -72.6705, -72.243, -71.67599999999995, -71.60624999999999, -70.95600000000005, -70.92000000000007, -70.37999999999998, -69.90750000000004, -69.79500000000002, -69.51599999999998, -69.20999999999998, -69.18300000000002, -68.92199999999994, -68.18849999999998, -67.90500000000003, -67.74750000000009, -67.64849999999998, -67.49100000000001, -66.14999999999998, -65.73599999999999, -64.02599999999993, -63.98549999999997, -63.89099999999996, -63.78299999999996, -63.324, -63.28800000000001, -62.986500000000035, -62.905500000000046, -62.66250000000002, -62.45100000000002, -62.30699999999996, -62.30024999999996, -62.04149999999993, -61.964999999999975, -61.89299999999996, -61.53750000000005, -61.22700000000003, -60.349499999999864, -59.80499999999999, -59.791499999999914, -59.363999999999805, -59.17500000000001, -58.009499999999974, -57.92399999999999, -57.65849999999999, -57.5775, -57.23999999999995, -57.2355, -57.068999999999974, -57.04200000000002, -56.71800000000002, -56.684999999999974, -56.64149999999998, -56.57849999999998, -56.05199999999991, -55.635000000000055, -55.39950000000004, -55.32300000000005, -54.79687499999999, -54.724500000000006, -54.553499999999985, -54.377999999999986, -53.99819999999996, -53.91599999999996, -53.302499999999995, -53.095500000000015, -53.03700000000002, -53.03280000000001, -53.01300000000005, -52.942500000000024, -52.71750000000002, -52.70849999999996, -52.69500000000002, -52.375500000000045, -52.24050000000003, -52.10549999999999, -52.09650000000002, -51.781500000000065, -51.60900000000001, -51.59250000000002, -51.46949999999999, -51.169500000000006, -51.16500000000001, -51.14250000000001, -50.93549999999999, -50.620500000000035, -50.55150000000005, -50.38650000000001, -50.296499999999995, -50.07599999999999, -50.05350000000008, -49.98149999999984, -49.84649999999999, -49.73849999999999, -49.598999999999975, -49.225500000000025, -49.163999999999994, -49.113000000000014, -49.023000000000025, -48.79350000000002, -48.76650000000004, -48.69449999999995, -48.6696, -48.63600000000004, -48.595500000000044, -48.46950000000001, -48.13200000000004, -48.100500000000025, -47.97900000000001, 41.17499999999991, 41.199, 41.20350000000002, 41.4405, 41.47799999999995, 41.571000000000005, 41.92949999999995, 42.082499999999975, 42.11400000000002, 42.227999999999994, 42.24599999999998, 42.298874999999995, 42.31349999999992, 42.484500000000025, 42.58305, 42.59699999999992, 42.601500000000044, 43.16849999999995, 43.32149999999997, 43.84500000000001, 43.871999999999844, 43.889999999999986, 43.91999999999999, 44.06999999999995, 44.09549999999999, 44.22150000000002, 44.22599999999991, 44.23650000000001, 44.459999999999994, 44.53649999999999, 44.61074999999998, 44.621999999999986, 44.67449999999999, 44.75249999999997, 44.81684999999999, 45.04049999999998, 45.062250000000006, 45.06299999999992, 45.21599999999998, 45.26549999999993, 45.37950000000001, 45.387, 45.4725, 45.55574999999997, 45.616500000000016, 45.64725, 45.836999999999975, 45.95399999999999, 46.09799999999998, 46.19699999999999, 46.27799999999998, 46.38599999999994, 46.43100000000002, 46.54987499999996, 46.58025000000002, 46.656, 46.68749999999999, 46.71262500000002, 46.818, 47.191499999999934, 47.218500000000006, 47.245499999999964, 47.560500000000005, 48.028499999999994, 48.046499999999995, 48.07349999999996, 48.53610000000003, 48.5505, 48.626999999999995, 48.887249999999995, 48.88912499999999, 49.01399999999999, 49.1255, 49.28249999999997, 49.33799999999994, 49.33800000000005, 49.679999999999964, 49.815, 49.864499999999964, 49.948499999999974, 50.251500000000064, 50.489249999999984, 50.542499999999976, 50.705999999999975, 50.83649999999997, 50.85600000000001, 51.55649999999996, 51.72749999999999, 52.36424999999994, 52.47450000000012, 52.60949999999998, 52.74449999999993, 52.90199999999996, 52.92, 53.24399999999994, 53.433000000000014, 53.739000000000004, 53.88449999999998, 54.076499999999996, 54.07650000000005, 54.08174999999999, 54.38699999999998, 54.39149999999995, 54.812325, 54.833999999999904, 55.322999999999865, 55.67849999999997, 56.121749999999935, 56.23200000000003, 56.26349999999999, 56.55150000000002, 56.600999999999985, 56.841750000000005, 56.88814285714281, 57.11849999999997, 57.194999999999965, 57.22199999999994, 57.708, 58.007999999999996, 58.09949999999995, 58.36049999999996, 58.642071428571384, 58.75649999999999, 58.87949999999995, 58.891500000000065, 59.27174999999997, 59.319000000000074, 59.386499999999984, 59.571, 59.84999999999997, 59.91750000000005, 60.21449999999999, 60.286499999999975, 60.317999999999955, 60.43950000000001, 61.64549999999997, 61.660499999999985, 61.81499999999998, 61.81949999999998, 61.88850000000001, 62.360999999999976, 62.39249999999996, 63.12824999999998, 63.248999999999995, 63.30825000000001, 63.6299999999998, 63.728999999999985, 64.04400000000001, 64.17449999999998, 64.46249999999998, 64.57499999999997, 65.03099999999999, 65.27249999999998, 65.49187499999996, 65.65650000000004, 65.76750000000007, 66.04312499999996, 66.59099999999998, 66.93300000000005, 67.32, 67.54907142857142, 67.97699999999999, 68.05514285714284, 68.43149999999996, 68.54850000000008, 69.38999999999997, 70.24950000000003, 70.32150000000001, 70.37999999999994, 70.45200000000006, 70.52850000000007, 70.60950000000001, 70.63199999999999, 71.26199999999997, 71.39100000000005, 71.63999999999993, 72.56549999999999, 72.57149999999996, 73.05899999999994, 73.72350000000002, 73.75499999999997, 73.77899999999997, 73.91699999999999, 75.15449999999998, 75.25799999999987, 75.47399999999998, 75.61529999999999, 75.85349999999998, 75.93299999999999, 76.10399999999993, 76.47974999999991, 77.08500000000001, 77.16599999999998, 77.8185, 77.98949999999992, 77.98949999999995, 78.67799999999995, 78.84900000000002, 79.17149999999995, 80.89312499999996, 81.28800000000007, 81.35999999999996, 81.46349999999998, 81.96524999999997, 82.01249999999999, 82.31399999999994, 83.13000000000008, 83.96550000000006, 84.3885, 84.65849999999995, 84.81599999999995, 85.25699999999992, 85.30199999999996, 85.49249999999999, 85.56299999999996, 85.82849999999996, 85.86449999999994, 86.11650000000012, 87.70049999999993, 88.65449999999993, 88.69950000000009, 88.78950000000002, 88.90200000000004, 89.82899999999997, 91.91850000000007, 92.13749999999999, 92.22750000000005, 92.39219999999997, 94.1445, 95.47199999999998, 97.39799999999988, 99.5265, 99.59400000000005, 100.863, 101.06819999999995, 101.70900000000003, 102.55050000000006, 102.82949999999995, 102.83399999999997, 103.13549999999998, 103.38524999999998, 103.4325, 109.05300000000011, 109.71899999999997, 111.22200000000002, 111.37499999999999, 111.47062499999998, 112.09971428571424, 112.63950000000011, 112.65525, 113.2605, 114.15600000000006, 115.55549999999995, 118.13850000000002, 118.65150000000011, 120.177, 122.0175, 123.183, 124.93800000000002, 124.95150000000001, 125.07600000000001, 126.78300000000002, 132.16950000000003, 137.54250000000002, 140.9625, 141.47324999999998, 141.98962499999996, 144.02249999999995, 144.55800000000008, 150.29550000000006, 154.19699999999997, 159.22799999999995, 160.02075, 160.94699999999995, 162.468, 163.49849999999998, 164.03850000000003, 167.96699999999998, 169.49250000000006, 194.15699999999998, 227.13750000000007, 227.454, 286.12800000000016, 354.8115000000001, 448.00649999999985, 614.3985]
In [23]:
plt.hist(x_test2['resid'], bins=30)
plt.show()
In [24]:
fig1 = go.Figure(
    go.Scattermapbox(
        lon=x_test2['longitude'],
        lat=x_test2['latitude'],
        mode='markers',
        marker_color=x_test2['resid'],
        text=x_test2['resid'],
        marker=dict(
            opacity=0.8,
            colorscale=[
                [0.0, "rgb(165,0,38)"],
                [0.11, "rgb(215,48,39)"],
                [0.22, "rgb(244,109,67)"],
                [0.33, "rgb(253,174,97)"],
                [0.44, "rgb(254,224,144)"],
                [0.55, "rgb(224,243,248)"],
                [0.66, "rgb(171,217,233)"],
                [0.77, "rgb(116,173,209)"],
                [0.88, "rgb(69,117,180)"],
                [1.0, "rgb(49,54,149)"]
            ]
        )
    )
)

fig1.update_layout(
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':x_test2['latitude'].mean(), 'lon':x_test2['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig1.show()

Coordenadas

In [25]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('COORD', cols, dfd)
NO-GEO COORD
R2 0.623 0.635
MAE 18.507 18.062
MSE 947.353 917.131

Barrios

In [26]:
cols = features.copy()
for c in [*dist_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('NB', cols, dfd)
NO-GEO COORD NB
R2 0.623 0.635 0.634
MAE 18.507 18.062 18.085
MSE 947.353 917.131 918.968

Cluster de barrios

In [27]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *coord_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('CLUSTER-NB', cols, dfd)
NO-GEO COORD NB CLUSTER-NB
R2 0.623 0.635 0.634 0.635
MAE 18.507 18.062 18.085 18.082
MSE 947.353 917.131 918.968 916.908

Distancias a puntos de interés

In [28]:
cols = features.copy()
for c in [*neighbourhood_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('DIST', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST
R2 0.623 0.635 0.634 0.635 0.637
MAE 18.507 18.062 18.085 18.082 18.070
MSE 947.353 917.131 918.968 916.908 911.900

Voronoi

In [29]:
cols = features.copy()
for c in [*neighbourhood_cols, *nb_cluster_cols, *coord_cols, *dist_cols, *s2_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('VORONOI', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI
R2 0.623 0.635 0.634 0.635 0.637 0.636
MAE 18.507 18.062 18.085 18.082 18.070 18.241
MSE 947.353 917.131 918.968 916.908 911.900 915.041

S2

In [30]:
cols = features.copy()
for c in [*neighbourhood_cols, *nb_cluster_cols, *coord_cols, *dist_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('S2', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI S2
R2 0.623 0.635 0.634 0.635 0.637 0.636 0.634
MAE 18.507 18.062 18.085 18.082 18.070 18.241 18.084
MSE 947.353 917.131 918.968 916.908 911.900 915.041 920.060

Automated feature engineering

In [31]:
auto_df = df.copy()
auto_df['auto_id'] = auto_df['price'].apply(lambda x: uuid.uuid1().int)
prices = auto_df['price']
auto_df.drop(['price'], axis=1, inplace=True, errors='ignore')
In [32]:
es = ft.EntitySet(id='airbnb')
es = es.entity_from_dataframe(
    entity_id='main',
    dataframe=auto_df,
    index='auto_id'
)
In [33]:
# available_transform_primitives = ft.primitives.list_primitives()
# print(available_transform_primitives[available_transform_primitives['type'] == 'transform'])

features_df, feature_names = ft.dfs(
    entityset=es,
    target_entity='main',
    trans_primitives=['subtract_numeric'],
    max_depth=2
)

# print(features_df.columns)
In [37]:
auto_df = features_df.copy()
auto_df.reset_index()
auto_df.drop(['auto_id'], axis=1, inplace=True, errors='ignore')

auto_df = pd.get_dummies(auto_df)
print(auto_df.shape)

auto_features = list(auto_df.columns)

x_train, x_test, y_train, y_test = train_test_split(
    auto_df, 
    prices,
    random_state=42
)

x_train = x_train.astype(float) # prevent conversion warnings
(17756, 1475)
In [38]:
y_pred = eval_model('AUTO-FT', auto_features, auto_df)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI S2 AUTO-FT
R2 0.623 0.635 0.634 0.635 0.637 0.636 0.634 0.636
MAE 18.507 18.062 18.085 18.082 18.070 18.241 18.084 17.835
MSE 947.353 917.131 918.968 916.908 911.900 915.041 920.060 913.109